import {createRouter, createWebHashHistory} from 'vue-router';

import {RouterObject} from './interface/index';

import NProgress from '@/utils/nprogress';
import Home from './modules/home';
import DepartmentManage from './modules/departmentManage';
import Administrator from "./modules/administrator";
import ApplyAdmin from "./modules/applyAdmin";
import ShopManage from "./modules/shopManage";
import ShopOperate from "./modules/shopOperate";
import StaffManage from "./modules/staffManage";
// * 导入所有router
const metaRouters = import.meta.glob('./modules/*.ts', {eager: true});

// * 处理路由
export const routerArray: RouterObject[] = [];
// 遍历动态导入的模块
Object.values(metaRouters).forEach(module => {
  // 检查模块是否有导出
  if (typeof module === 'object' && module !== null) {
    Object.values(module).forEach(value => {
      // 检查值是否为数组
      if (Array.isArray(value)) {
        routerArray.push(...(value as RouterObject[]));
      }
    });
  }
});

const routes: RouterObject[] = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/pages/login/login.vue'),
  },
  ...Home,
  ...ShopManage,
  ...DepartmentManage,
  ...StaffManage,
  ...ApplyAdmin,
  ...ShopOperate,
  ...Administrator,
  // ...routerArray,
  {
    path: '/404',
    name: '404',
    component: () => import('@/pages/404.vue'),
    meta: {
      title: '404',
      noPermission: true,
    },
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, _from, next) => {
  NProgress.start();
  next();
});

router.afterEach((to, _from) => {
  NProgress.done();
});

export default router;
